/**
 * 
 */
package com.hp.bon.sgw.wh.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.wh.util.DateUtil;
import com.hp.bon.sgw.wh.utils.ThreeDESKeyParam;

/**
 * @author sunhaiy
 * 
 */

@Path("/")
public class TYConfigService {

	private static final Logger logger = LoggerFactory.getLogger(TYConfigService.class);
	private String whCfgFile = "./etc/wh_ty_config.properties";

	private volatile Configuration config;

	public void init() {
		this.loadCfgFile();
//		TYConfigTask configTask =new TYConfigTask();
//		configTask.start();
	}
	
	class TYConfigTask extends Thread {
		public void run(){
			while(true){
				try {
					sleep(30*60*1000);
					String gentime =getValue("GENTIME", "");
					String validtime =getValue("VALIDTIME", "");
					if(DateUtil.isVALID(gentime,validtime)){
						String result =updateCfgFile();
						if("SUCCESS".equals(result)){
							postHttpReq("", getValue("ReloadCfgFileUrl", ""));
						}
					}
				} catch (Exception e1) {
					logger.error("task Exception! "+ e1.getMessage());
				}
			}
		}
	}

	@GET
	@Path("tyConfig/reload")
	@Produces(MediaType.APPLICATION_JSON)
	public String loadCfgFile() {
		logger.info("[TYConfigService] load properties file - " + whCfgFile+ " start...");
		boolean isSuccess = true;
		File paramFile = new File(whCfgFile);
		InputStreamReader in = null;
		PropertiesConfiguration propConfig = new PropertiesConfiguration();
		try {
			in = new InputStreamReader(new BufferedInputStream(new FileInputStream(paramFile)), "utf-8");
			propConfig.setDelimiterParsingDisabled(true);
			propConfig.load(in);
			propConfig.setAutoSave(true);
		} catch (Exception e) {
			logger.warn("load properties file - exception ignored", e);
			isSuccess = false;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				logger.error("load properties file", e);
				e.printStackTrace();
			}
		}
		config = propConfig;

		logger.info("[TYConfigService] load properties file - " + whCfgFile+ (isSuccess ? " SUCCESS" : " FAILED"));
		return isSuccess ? "SUCCESS" : "FAILED";
	}
	
	@GET
	@Path("tymyConfig/reloadCfgFile/{resultKey}/{gentime}/{validTime}")
	@Produces(MediaType.APPLICATION_JSON)
	public String reloadCfgFile(@PathParam("resultKey") String resultKey,@PathParam("gentime") String gentime,@PathParam("validTime") String validTime) {
		logger.info("[TYMYConfigService reloadCfgFile] start...");
		boolean isSuccess = true;
		config.setProperty("KEY", resultKey);     
        config.setProperty("GENTIME", gentime);    
        config.setProperty("VALIDTIME", validTime);  
		return isSuccess ? "SUCCESS" : "FAILED";
	}
	
	@GET
	@Path("tymyConfig/reload")
	@Produces(MediaType.APPLICATION_JSON)
	public String updateCfgFile() {
		logger.info("[TYMYConfigService updateCfgFile] start...");
		boolean isSuccess = true;
		HashMap<String,String> ResultMap =getTranKey();
		if(!ResultMap.get("RESPONSECODE").equals("000000")){
			isSuccess=false;
		}
		return isSuccess ? "SUCCESS" : "FAILED";
	}
	
	

	private HashMap<String,String> getTranKey()//
	  {
	    logger.info("=================================翼支付交费助手签到获取交易密钥===============begin===============");
	    
	    String tranKey = "";
	    String validTime = "";
	    String resultKey = "";
	    String gentime="";

	    String key=getValue("KEY", "");
	    
	   //测试数据2
	    TimeZone zone = TimeZone.getTimeZone("GMT+8");
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
	    formatter.setTimeZone(zone);
	    Date currentTime = new Date();
	    String sysDate = formatter.format(currentTime);

	    String responSecode = "";
	    String responSecontent = "";

	    HashMap<String,String> ResultMap = new HashMap<String,String>();
	    try
	    {
	      StringBuffer params = new StringBuffer();
	      params.append("{\"PARAMS\":{");
	      params.append("\"VALIDPERIOD\":");
	      params.append("\"3\",");
	      params.append("\"OLDTRANKEY\":");

	      params.append("\"" + key + "\",");
	      params.append("\"ACCEPTORGCODE\":");

	      params.append("\"" + getValue("ACCEPTORGCODE", "")+ "\",");
	      params.append("\"KEYTYPE\":");
	      params.append("\"1\",");
	      params.append("\"ACCEPTTIME\":");

	      params.append("\"" + sysDate + "\"},");
	      params.append("\"APP_CODE\":");
	      params.append("\""+getValue("APP_CODE", "")+"\",");
	      params.append("\"IP\":");

	      params.append("\"" + getValue("IP", "") + "\",");
	      params.append("\"SERVICE_CODE\":");
	      params.append("\"P10000\",");
	      params.append("\"VERSION\":");
	      params.append("\""+getValue("VERSION", "")+"\"}");

	      logger.info("======获取交易密钥=======要加密的明文内容=" + params.toString());

	      ThreeDESKeyParam des = ThreeDESKeyParam.getInstance();
	      String strEnc = des.getEncString(params.toString(), key);

	      String json = "{\"REQ_HEAD\":{\"ACCEPTORGCODE\":\"" + getValue("ACCEPTORGCODE", "") + "\"},\"REQ_BODY\":{\"ENCRYPTSTR\":\"" + strEnc + "\"}}";
	      logger.info("======获取交易密钥=======发送给集团包含密文的字符串=" + json);
	      
	      String reqText = postHttpReq(json, getValue("SecretKeyUrl", ""));
	      
//	      reqText = new String(reqText.getBytes("ISO8859-1"), "UTF-8");
	      logger.info("======获取交易密钥=======集团返回的包含密文的字符串=" + reqText);

	      JSONObject jsonObject = JSONObject.fromObject(reqText);
	      String repHead = jsonObject.getString("RSP_HEAD");
	      logger.info("======获取交易密钥返回的消息RSP_HEAD=" + repHead);

	      JSONObject jsonRepHead = JSONObject.fromObject(repHead);
	      responSecode = jsonRepHead.getString("RESPONSECODE");
	      logger.info("======获取交易密钥返回的消息RESPONSECODE=" + responSecode);

	      responSecontent = jsonRepHead.getString("RESPONSECONTENT");
	      logger.info("======获取交易密钥返回的消息RESPONSECONTENT=" + responSecontent);

	      if (responSecode.equals("000000"))
	      {
	        String rspBody = jsonObject.getString("RSP_BODY");
	        logger.info("=====获取交易密钥返回的消息，需要解密的RSP_BODY=" + rspBody);
	        JSONObject jsonRspBody = JSONObject.fromObject(rspBody);
	        String encryptStr = jsonRspBody.getString("ENCRYPTSTR");
	        logger.info("=====获取交易密钥返回的消息，需要解密的串ENCRYPTSTR=" + encryptStr);

	        String	strDes = des.getDesString(encryptStr, key);
	        jsonObject = JSONObject.fromObject(strDes);
	        JSONArray arrayResult = jsonObject.getJSONArray("RESULTDATASET");
	        for (int i = 0; i < arrayResult.length(); i++) {
	          String tranKeyJon = arrayResult.get(i).toString();
	          logger.info("======第一次解密后得到的JSON对像=" + tranKeyJon);
	          jsonObject = JSONObject.fromObject(tranKeyJon);
	          tranKey = jsonObject.getString("TRANKEY");
	          logger.info("======解析JSON对像得到交易密钥TRANKEY=" + tranKey);
	          validTime = jsonObject.getString("VALIDTIME");
	          logger.info("======解析JSON对像得到有效周期VALIDTIME=" + validTime);
	          gentime = jsonObject.getString("GENTIME");
	          logger.info("======解析JSON对像得到有效周期VALIDTIME=" + validTime);
	          resultKey = des.getDesString(tranKey, key);
	          logger.info("======对交易密钥TRANKEY进行第二次解密后得到最终的KEY=" + resultKey);
	        }
	        
	        config.setProperty("KEY", resultKey);     
	        config.setProperty("GENTIME", gentime);    
	        config.setProperty("VALIDTIME", validTime);    
	      }
	      else
	      {
	        logger.info("======调用集团时返回错误RESPONSECODE=" + responSecode + "  RESPONSECONTENT=" + responSecontent);
	      }
	      logger.info("====================================翼支付交费助手签到获取交易密钥===============end===============");
	      ResultMap.put("RESPONSECODE", responSecode);
	      ResultMap.put("RESPONSECONTENT", responSecontent);
	      ResultMap.put("RESUTLKEY", resultKey);
	      ResultMap.put("VALIDTIME", validTime);
	      
	    }
	    catch (Throwable e) {
	      logger.info("翼支付交费助手签到获取交易密钥失败" + e.getMessage());
	      ResultMap.put("RESPONSECODE", "-1");
	      ResultMap.put("RESPONSECONTENT", "翼支付交费助手签到获取交易密钥失败");
	      return ResultMap;
	    }
	    return ResultMap;
	  }
	 
	 
	 private static  String postHttpReq(String json, String url) {
		HttpClient httpClient = new HttpClient();

		byte b[] = json.getBytes();// 把字符串转换为二进制数据
		RequestEntity requestEntity = new ByteArrayRequestEntity(b);

		EntityEnclosingMethod postMethod = new PostMethod();
		postMethod.setRequestEntity(requestEntity);// 设置数据
		postMethod.setPath(url);// 设置服务的url
		// postMethod.setRequestHeader("Content-Type",
		// "application/soap+xml; charset=UTF-8");// 设置请求头编码
		httpClient.getParams().setContentCharset("UTF-8");
		// 设置连接超时
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);
		// 设置读取超时
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(20 * 1000);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);

		String responseMsg = "";
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);// 发送请求
			responseMsg = postMethod.getResponseBodyAsString();// 获取返回值
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();// 释放连接
		}

		if (statusCode != HttpStatus.SC_OK) {
			logger.info("HTTP服务异常" + statusCode);
		}
		return responseMsg;
	}
	 
	public String getValue(String name, String defaultValue) {
		return config.getString(name, defaultValue);
	}

	public int getIntValue(String name, int defaultValue) {
		return config.getInt(name, defaultValue);
	}

	public double getDoubleValue(String name, double defaultValue) {
		return config.getDouble(name, defaultValue);
	}

	public long getLongValue(String name, long defaultValue) {
		return config.getLong(name, defaultValue);
	}

	public boolean getBooleanValue(String name, boolean defaultValue) {
		return config.getBoolean(name, defaultValue);
	}
}
